package com.sc.feign.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        Map<String,String> headers = getHeaders();
        for(String headerName : headers.keySet()){
            requestTemplate.header(headerName, headers.get(headerName));
        }
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            if(requestAttributes != null){
                return ((ServletRequestAttributes)requestAttributes).getRequest();
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private Map<String, String> getHeaders() {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = getHttpServletRequest().getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = getHttpServletRequest().getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}
